//
//  File.cpp
//  mytest
//
//  Created by 杨岑 on 7/15/14.
//
//

#include "TestLayer.h"
#include "CCBILoader.h"

bool TestLayer::init()
{
    if (!super::init()) return false;

    return true;
}

void TestLayer::initLayout()
{
    Size mySize = this->getContentSize();
    
    const char* ccbiFile = "ccbi/TestLayer.ccbi"; // .ccbi file extension is not required
    BEGIN_CCBI_LOADER3(ccbiFile, this, mySize)
    CCBI_ROOT_PATH("ccbi/")
    CCBI_MEMBER2("root", _ccbiLayer)
    CCBI_MEMBER(_bk)
    CCBI_MEMBER(_bgSprite)
    CCBI_MEMBER(_bgLayer)
    CCBI_MEMBER(_colorLayer)
    CCBI_MEMBER(_helloLabel)
    CCBI_MEMBER(_testMenuItem)
    CCBI_MEMBER(_testButton)
    CCBI_MEMBER_ARRAY(_sprites, 10, _numSprites)
    CCBI_MENU_HANDLER("testMenuItemClick", TestLayer::testMenuItemClick)
    CCBI_CONTROL_HANDLER("testButtonClick", TestLayer::testButtonClick)
    END_CCBI_LOADER
    
    CCLOG("%lu sprites found", _numSprites);
    Size bkSize = _bk->getContentSize();
    _bk->setScale(mySize.width / bkSize.width, mySize.height / bkSize.height);
    
    Size bgLayerSize = _bgLayer->getContentSize();
    Size bgSpriteSize = _bgSprite->getContentSize();
    _bgSprite->setScale(bgLayerSize.width / bgSpriteSize.width, bgLayerSize.height / bgSpriteSize.height);
    
    this->addChild(_ccbiLayer);
    Size ccbiLayerSize = _ccbiLayer->getContentSize();

    CCLOG("TestLayer size: %f, %f", mySize.width, mySize.height);
    CCLOG("CCBI layer size: %f, %f", ccbiLayerSize.width, ccbiLayerSize.height);

    //_helloLabel->setString("Loaded");
}

void TestLayer::testButtonClick(cocos2d::Ref *sender, Control::EventType eventType)
{
    CCLOG("testButtonClick");
    this->fadeMeOut();
}

void TestLayer::testMenuItemClick(Ref* sender)
{
    CCLOG("testMenuItemClick");
}

void TestLayer::onEnter()
{
    super::onEnter();
}

void TestLayer::onExit()
{
    super::onExit();
}

void TestLayer::fadeMeOut()
{
    Size mySize = this->getContentSize();
    
 	auto rt = RenderTexture::create((int)mySize.width, (int)mySize.height, Texture2D::PixelFormat::RGBA8888);
    //this->addChild(rt);
    //rt->setPosition(mySize.width / 2, mySize.height / 2);
    rt->setAutoDraw(true);
    
	rt->begin();
	_ccbiLayer->visit();
    rt->end();
    
    _ccbiLayer->setVisible(false);
    
    auto img = Sprite::createWithTexture(rt->getSprite()->getTexture());
    img->setBlendFunc(BlendFunc::ALPHA_NON_PREMULTIPLIED);
    img->setPosition(mySize.width / 2, mySize.height / 2);
    img->setFlippedY(true);
    this->addChild(img);
    
    auto fadeOut = FadeOut::create(2.5);
    auto done = CallFunc::create(std::bind([this, img] {
        //img->removeFromParent();
        this->removeFromParent();
    }));
    
    img->runAction(Sequence::create(fadeOut, done, nullptr));
}

